package com.nchu.learn.netty.resolver;

import com.nchu.learn.netty.enums.MessageTypeEnum;
import com.nchu.learn.netty.model.Message;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fujianjian
 * @project self-learning
 * @date 2020/1/16 11:33
 */
@Slf4j
public class RequestMessageResolver implements Resolver {

    private static final AtomicInteger counter = new AtomicInteger(1);

    @Override
    public Message resolve(Message message) {
        // 接收到消息进行处理，demo只是做打印处理
        int index = counter.getAndIncrement();
        log.info("[trx: {}] {} . receive request:{}",
                message.getSessionId(), index, message.getBody());
        log.info("[trx:{}] {} . attachments:",
                message.getSessionId(), index, message.getAttachments());

        // 处理完成后生成一个响应消息返回
        Message response = new Message();
        response.setMessageType(MessageTypeEnum.RESPONSE);
        response.setBody("nice to meet you too!");
        response.addAttachment("name", "allen");
        response.addAttachment("city", "shanghai");
        response.addAttachment("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return response;
    }

    @Override
    public boolean support(Message message) {
        return message.getMessageType() == MessageTypeEnum.REQUEST;
    }
}
